// pages/my-pages/swiper-edit/index.js
const httpUtils = require('../../../utils/httpUtils')
const ui = require('../../../utils/ui')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    originFiles: [],
  },

  //选择文件完成
  handleAdd: function (e) {
    console.log("handleAdd 事件")
    let baseUrl = httpUtils.getBaseUrl();
    let that = this;
    const {
      files
    } = e.detail;
    console.log("files:" + JSON.stringify(files))
    wx.showLoading({
      title: '图片上传中.....',
    });
    let completeNum = 0;
    for (let index = 0; index < files.length; index++) {
      const uploadFilePromise = new Promise(function (resolve, reject) {
        wx.uploadFile({
          filePath: files[index].url,
          name: 'file',
          url: baseUrl + '/file/miniUpload',
          formData: {},
          header: {
            'Content-Type': 'application/json',
            'X-Access-Token': wx.getStorageSync('token')
          },
          success: (res) => {
            console.log(res)
            if (res.statusCode == 200) {
              resolve(res.data);
            }
          }
        })
      });
      // 等待上传完成后执行其他操作
      uploadFilePromise.then(function (result) {
        // 在这里可以执行上传完成后的逻辑
        console.log('文件上传成功，返回结果：', result);
        completeNum++;
        const arr = result.split("/");
        let fileName = arr[arr.length - 1];
        let file = {
          url: result,
          name: fileName,
          type: "image"
        }
        that.data.originFiles.push(file);
        that.setData({
          originFiles: that.data.originFiles
        });
        if (completeNum == files.length) {
          wx.hideLoading();
        }
      });
    }
  },

  //点击删除事件
  handleRemove(e) {
    console.log("handleRemove 事件")
    const {
      index
    } = e.detail;
    const {
      originFiles
    } = this.data;
    originFiles.splice(index, 1);
    this.setData({
      originFiles,
    });
  },

  //点击图片
  handleClick(e) {
    console.log("handleClick 事件")
    console.log(e.detail.file);
  },

  //查询用户轮播图列表
  getSwiperList: function(){
    let that = this;
    let obj = {
      method: 'GET',
      showLoading: true,
      url: 'swiper/getSwiperDetailList'
    }
    httpUtils.request(obj).then(res => {
      if (res.data.retCode == 0) {
        that.setData({
          originFiles: res.data.data
        })
      } else {
        ui.showToast(res.data.message)
      }
    }).catch(err => {
      ui.showToast('请求失败')
    });
  },
  //点击保存
  confirmSaveButton: function () {
    let that = this;
    let fileList = that.data.originFiles;
    let fileUrlList = [];
    if (undefined != fileList && 'null' != fileList && fileList.length > 0) {
      for (let index = 0; index < fileList.length; index++) {
        fileUrlList.push(fileList[index].url);
      }
    }
    let obj = {
      method: 'POST',
      showLoading: true,
      url: 'swiper/saveSwiper',
      data: {
        'swiperFiles': fileUrlList
      }
    }
    httpUtils.request(obj).then(res => {
      if (res.data.retCode == 0) {
        ui.showToast('保存成功')
        wx.navigateBack({
          detail: 1
        })
      } else {
        ui.showToast(res.data.message)
      }
    }).catch(err => {
      ui.showToast('请求失败')
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getSwiperList()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})